package com.fang.demo01.controller;

import com.fang.demo01.entity.Book;
import com.fang.demo01.repository.BookRepository;
import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.CriteriaBuilder;
import java.util.List;

/**
 * Create By Li
 * Fang on 2020/12/4.
 */
@RestController
@RequestMapping("/book")
public class BookHandler {
    @Autowired
    private BookRepository bookRepository;

    //让前端传参数过来
    @GetMapping("/findAll/{page}/{size}")
    //将参数都取出来（） //发现加上required=false，地址栏不加参数，还是404报错，加上value={"","/findAll"}，还是不行，因此这里必须要绑定参数
    public Page<Book> findAll(@PathVariable(value = "page") Integer page, @PathVariable(value = "size") Integer size) {
        // 将page和size都传进去
        Pageable pageable = PageRequest.of(page - 1, size);
        return bookRepository.findAll(pageable);
    }

    //基于restful， 应该添加 @PostMapping注解   //前端用json格式将对象传过来,因此后端需要加@RequestBody去映射(把json转为java对象)，
    @PostMapping("/savebook")
    public String save(@RequestBody Book book) {
        Book result = bookRepository.save(book);
        if (result != null) {
            return "success";

        } else {
            return "error";
        }

    }

    //通过id查询整条记录
    @GetMapping("/findById/{id}")
    public Book findById(@PathVariable("id") Integer id) {
        return bookRepository.findById(id).get();
    }
    //删除
    @DeleteMapping("/deleteById/{id}")
    public void deleteById(@PathVariable("id") Integer id){
        bookRepository.deleteById(id);

    }
}
